package com.yifi.common;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.ServletContext;

import com.jfinal.core.JFinal;
import com.jfinal.render.Render;
import com.jfinal.render.RenderException;
import com.jfinal.render.RenderFactory;

//重写renderFile，解决中文乱码,支持重命名,支持删除文件
//http://my.oschina.net/u/935698/blog/107363
public class FileRender extends Render {

    private File file;
    private String filename;
    private boolean delfile;
    private ServletContext servletContext;
     
    public FileRender(File file) {
        this.file = file;
        this.filename =file.getName();
        this.delfile = false;
        this.servletContext =  JFinal.me().getServletContext();
    }

    public FileRender(String fname,String furl,boolean isdel) {
        this.file = new File(furl);
    	this.filename = fname;
        this.delfile = isdel;
        this.servletContext =  JFinal.me().getServletContext();
    }
 
    @Override
    public void render() {
         
        if (file == null || !file.isFile() || file.length() > Integer.MAX_VALUE) {
            new RenderFactory().getErrorRender(404).setContext(request, response).render();
            return ;
        }
        //源码中的代码
        //response.addHeader("Content-disposition", "attachment; filename=" + file.getName());
        //修改后的代码 解决中文乱码问题
        try {
            response.addHeader("Content-disposition", 
                "attachment; filename=" + URLEncoder.encode(this.filename, "UTF-8"));//new String(file.getName().getBytes("GBK"), "ISO8859-1"));
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        String contentType = servletContext.getMimeType(file.getName());
        if (contentType == null) {
            contentType =  "application/octet-stream";
        }
         
        response.setContentType(contentType);
        response.setContentLength((int)file.length());
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = new BufferedInputStream(new FileInputStream(file));
            outputStream = response.getOutputStream();
            byte[] buffer = new byte[1024];
            for (int n = -1; (n = inputStream.read(buffer)) != -1;) {
                outputStream.write(buffer, 0, n);
            }
            outputStream.close();
            inputStream.close();
            if(this.delfile)//删除文件
            {
            	this.file.delete();
            }
        }
        catch (Exception e) {
            throw new RenderException(e);
        }
    }
     
     
}

